﻿
Option Explicit On
'*******************************************************************
' Program: pkgVisio
' Author: Albert E Edlund
' Date:
'
' Purpose:
' Working with office object XML
'
'*******************************************************************

#Region " imports "


Imports System
Imports System.Object
Imports System.IO
Imports System.IO.TextReader
' need to reference windowsbase in .net
Imports System.IO.Packaging

' need for dbconnectionstringbuilder used in clsConnections
Imports System.Data.Common

Imports System.Windows
Imports System.Windows.Forms
Imports System.Text.StringBuilder

Imports Microsoft.VisualBasic

Imports System.Text
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Imports System.Xml
Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Windows.Input

Imports System.Xml.Serialization
Imports System.Xml.Linq
Imports System.Xml.XPath

Imports ADODB
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Sql


Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging


' visio v15 does not use a xName prefix which may put it into conflict with other open office apps
Imports <xmlns="http://schemas.microsoft.com/office/visio/2012/main">
Imports <xmlns:rs="urn:schemas-microsoft-com:rowset">

' generic namespace for office open xml, used in all of them
Imports <xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">

'Imports pkgVisio.clsVisPackage
'Imports pkgVisio.clsShape

Imports pkgVisio.clsStructures

#End Region


'**********************************************************************************
'
' the pages file holds the attributes and elements for each of the pages's, it
' also hold the resource id that points to the page file with their shape and 
' connectivity information
'
'**********************************************************************************
'
Public Class clsPages


#Region " Properties and Declarations "


    '
    '
    '
    Private m_dictPagesNameU As Dictionary(Of String, stcPageData)
    Public Property dictPagesNameU As Dictionary(Of String, stcPageData)
        Get
            dictPagesNameU = Me.m_dictPagesNameU
        End Get
        Set(value As Dictionary(Of String, stcPageData))
            Me.m_dictPagesNameU = value
        End Set
    End Property

    '
    '
    '
    Private m_dictPagesID As Dictionary(Of Integer, stcPageData)
    Public Property dictPagesID As Dictionary(Of Integer, stcPageData)
        Get
            dictPagesID = Me.m_dictPagesID
        End Get
        Set(value As Dictionary(Of Integer, stcPageData))
            Me.m_dictPagesID = value
        End Set
    End Property

    '
    '
    '
    Public _xDoc As XDocument
    Public Property xDoc As XDocument
        Get
            Return Me._xDoc
        End Get
        Set(value As XDocument)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "xDoc is Null.")
            End If
            Me._xDoc = value
        End Set
    End Property

    '
    '
    '
    Public m_visPackage As clsVisPackage
    Public Property visPackage As clsVisPackage
        Get
            visPackage = Me.m_visPackage
        End Get
        Set(value As clsVisPackage)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "visPackage is Null.")
            End If
            Me.m_visPackage = value
        End Set
    End Property

    '
    '
    '
    Private m_fileCurrent As String
    Public Property fileCurrent As String
        Get
            fileCurrent = Me.m_fileCurrent
        End Get
        Set(value As String)

            If ((value Is Nothing) Or (value = "")) Then
                Throw New System.ArgumentNullException("Value", _
                    "fileCurrent is Null.")
            End If
            Me.m_fileCurrent = value
        End Set
    End Property


    '
    '
    '
    Private m_visPage As clsPage
    Public Property visPage As clsPage
        Get
            visPage = Me.m_visPage
        End Get
        Set(value As clsPage)
            Me.m_visPage = value
        End Set
    End Property



#End Region


#Region " test strings "


    Public Const pagesHeaderXML As String = "<?xml version=""1.0"" encoding=""utf-8"" ?> " _
        & "<Pages xmlns=""http://schemas.microsoft.com/office/visio/2012/main"" " _
        & "xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" " _
        & "xml:space=""preserve""> " _
        & "</Pages>"




#End Region


    '
    ' load a list of page names and ids into a list control
    '
    Public Sub loadPages _
        (ByRef lvControl As ListView)


        Dim lngPgId As Long = -1
        Dim strPgName As String = ""
        Dim strPgNameU As String = ""
        Dim strPgRid As String = ""
        Dim strPgFile As String = ""


        Me.m_dictPagesNameU = Nothing
        Me.dictPagesNameU = New Dictionary(Of String, stcPageData)

        Me.m_dictPagesID = Nothing
        Me.dictPagesID = New Dictionary(Of Integer, stcPageData)

        Try


            Dim lvItem As ListViewItem

            Dim qryPages = Me.xDoc...<Page>
            Dim intPages As Integer = qryPages.Count
            Dim docPage As XDocument = Nothing

            If lvControl IsNot Nothing Then
                lvControl.Items.Clear()
                lvControl.Columns.Clear()
                lvControl.View = View.Details
                lvControl.AllowColumnReorder = True
                lvControl.FullRowSelect = True
                lvControl.Columns.Add("Id", 50, HorizontalAlignment.Right)
                lvControl.Columns.Add("Name", 100, HorizontalAlignment.Left)
                lvControl.Columns.Add("NameU", 100, HorizontalAlignment.Left)
                lvControl.Columns.Add("RelId", 50, HorizontalAlignment.Left)
                lvControl.Columns.Add("File", 150, HorizontalAlignment.Left)
            End If

            ' get the pagesheet information from the pages file
            For Each page In qryPages


                lngPgId = -1
                strPgName = "NoPgName"
                strPgNameU = "NoPgNameU"
                strPgRid = "NoResc"
                strPgFile = "NoFile"

                Dim listOfAttributes As IEnumerable(Of XAttribute) = _
                    From att In page.Attributes() _
                    Select att
                For Each att As XAttribute In listOfAttributes
                    ' Console.WriteLine("{0}={1}", att.Name.LocalName, att.Value)
                    Select Case LCase(att.Name.LocalName)
                        Case "id"
                            lngPgId = CLng(att.Value)
                        Case "name"
                            ' get the recordset name
                            strPgName = CStr(att.Value)
                        Case "nameu"
                            strPgNameU = CStr(att.Value)
                    End Select
                Next att

                ' get the relationship id
                Dim listofElements As IEnumerable(Of XElement) = _
                    From elem In page.Elements() _
                    Select elem
                For Each elem As XElement In listofElements
                    Select Case LCase(elem.Name.LocalName)
                        Case "rel"
                            strPgRid = CStr(elem.@r:id)
                    End Select
                Next elem

                ' go find the associated file
                For Each PkgPart In Me.visPackage.colPkgPartInfo
                    If PkgPart.pkgpartContentType = clsVisPackage.contXmlPage _
                        And PkgPart.pkgpartResourceId = strPgRid Then
                        strPgFile = PkgPart.pkgpartPath
                        Exit For
                    End If
                Next PkgPart


                Dim newPage As stcPageData = New stcPageData
                newPage.pgId = lngPgId
                newPage.pgName = strPgName
                newPage.pgNameU = strPgNameU
                newPage.pgResource = strPgRid
                newPage.pgFile = strPgFile
                Me.dictPagesNameU.Add(strPgNameU, newPage)
                Me.dictPagesID.Add(lngPgId, newPage)


                If lvControl IsNot Nothing Then
                    lvItem = New ListViewItem(lngPgId)
                    lvItem.SubItems.Add(strPgName)
                    lvItem.SubItems.Add(strPgNameU)
                    lvItem.SubItems.Add(strPgRid)
                    lvItem.SubItems.Add(strPgFile)

                    ' add it to the listview on the data page
                    lvControl.Items.Add(lvItem)
                End If ' test for control

            Next page

        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    '
    '
    Public Sub loadPagesXDoc(ByVal pkgSource As clsVisPackage)

        Me.visPackage = pkgSource

        Try
            If Me.visPackage.colPkgPartInfo.Count = 0 Then
                Me.visPackage.loadPkgAndParts()
            End If
            Dim colPkgParts As Collection(Of pkgpartInfo) = New Collection(Of pkgpartInfo)
            colPkgParts = Me.visPackage.getPkgPartsByContent(pkgVisio.clsVisPackage.contXmlPages)
            If colPkgParts.Count = 1 Then
                Dim tempPkgPart As pkgpartInfo = colPkgParts(0)
                Me.xDoc = Me.visPackage.getPackagePartAsXDoc(visPackage.fileCurrent, tempPkgPart)
            End If

        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub



    '
    ' pass in a dictPageShapes and load it with the page shape data
    '
    Public Function loadPageShapeDictionary() As Dictionary(Of stcPageShape, stcShapeInfo)

        Dim retDictionary As Dictionary(Of stcPageShape, stcShapeInfo) = New Dictionary(Of stcPageShape, stcShapeInfo)

        Try


            For Each PkgPart In Me.visPackage.colPkgPartInfo
                If PkgPart.pkgpartContentType = clsVisPackage.contXmlPage Then

                    ' start with a clean page
                    If Me.m_visPage IsNot Nothing Then
                        Me.m_visPage = Nothing
                    End If

                    ' go setup the pageid and pagenames because they came from the pages xelement
                    For Each page In dictPagesNameU
                        If LCase(page.Value.pgFile) = LCase(PkgPart.pkgpartPath) Then
                            Dim tempDoc As XDocument = Me.visPackage.getPackagePartAsXDoc(Me.visPackage.fileCurrent, PkgPart)
                            Me.visPage = New clsPage(Me.visPackage, tempDoc)
                            Me.visPage.lngPgId = CLng(page.Value.pgId)
                            Me.visPage.strPgNameU = page.Value.pgNameU
                            Me.visPage.strPgName = page.Value.pgName
                            Exit For
                        End If
                    Next page

                    If Me.m_visPage Is Nothing Then GoTo NextPkgPart

                    If Me.visPackage.dictPageShape Is Nothing Then
                        Me.visPackage.dictPageShape = New Dictionary(Of stcPageShape, stcShapeInfo)
                    End If
                    ' clear the local copy of the pageshape dictionary
                    Me.visPackage.dictPageShape.Clear()
                    ' load the local page shape dictionary
                    Me.visPackage.loadShapes(Me.visPage.xDoc, Me.visPage.lngPgId)

                    ' copy the unique id's to the referenced dictionary
                    If Me.visPackage.dictPageShape.Count > 0 Then
                        For Each visPageShape In Me.visPackage.dictPageShape
                            Try
                                Dim blnFound As Boolean = False
                                Try
                                    blnFound = retDictionary.ContainsKey(visPageShape.Key)
                                Catch err As System.Collections.Generic.KeyNotFoundException
                                End Try
                                If blnFound = False Then
                                    Dim newShape As stcShapeInfo = Me.visPackage.dictPageShape(visPageShape.Key)
                                    retDictionary.Add(visPageShape.Key, newShape)
                                End If
                            Catch err As System.Collections.Generic.KeyNotFoundException
                            End Try

                        Next visPageShape
                    End If ' test for shapes 

                End If ' test for page
NextPkgPart:
            Next PkgPart

            'Dim sbDictPage As StringBuilder = New StringBuilder
            'For Each shape In retDictionary
            '    Dim lngKeyPsPage As Long = shape.Key.psPage
            '    Dim lngKeyPsShape As Long = shape.Key.psShape
            '    Dim lngValPgId As Long = shape.Value.lngPgId
            '    Dim lngValShpId As Long = shape.Value.lngShpId
            '    Dim lngValShpParent As Long = shape.Value.lngShpParent
            '    Dim strValShpNameU As String = shape.Value.strShpNameU
            '    sbDictPage.AppendFormat(" {0} {1} : {2} {3} {4} {5}" & vbCrLf, _
            '                            lngKeyPsPage, lngKeyPsShape, _
            '                            lngValPgId, lngValShpId, lngValShpParent, strValShpNameU)
            'Next shape
            'Debug.Print(sbDictPage.ToString)


        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        loadPageShapeDictionary = retDictionary


    End Function



#Region " playing with pages "

    '
    ' pass in a package and a pagesummary xelement, update the pages pkgpart
    '
    Public Sub addPortraitPageToPagesPkgPart _
        (ByRef packageCurrent As Package, _
         Optional ByVal intNewPageId As Integer = 0, _
         Optional ByVal strNewPageName As String = "Page-1", _
         Optional ByVal strNewPagePath As String = "page1.xml", _
         Optional ByVal strNewRid As String = "rId1", _
         Optional ByVal xelemPageSummary As XElement = Nothing)

        Try

            Dim tempVisPackage As clsVisPackage = New clsVisPackage
            ' go get the template and create an xElement out of it
            Dim xelemNewPage As XElement = XElement.Load((XmlReader.Create(New StringReader(clsPage.pageTemplateXML))))

            xelemNewPage.SetAttributeValue("ID", CStr(intNewPageId))
            xelemNewPage.SetAttributeValue("Name", strNewPageName)
            xelemNewPage.SetAttributeValue("NameU", strNewPageName)

            ' get the relationship id
            Dim listofElements As IEnumerable(Of XElement) = _
                From elem In xelemNewPage.Elements() _
                Select elem
            For Each elem As XElement In listofElements
                Select Case LCase(elem.Name.LocalName)
                    Case "rel"
                        Dim attrRID As XAttribute = elem.Attributes.FirstOrDefault
                        attrRID.Value = strNewRid
                End Select
            Next elem


            Const bufSize As Integer = &H1000
            Dim uniEncoding As New UTF8Encoding
            Dim byteXML As Byte()

            ' go get the pages package part
            Me._xDoc = Nothing
            Dim pkgpartPages As PackagePart = Nothing
            Dim pagesPath As String = "/visio/pages/pages.xml"
            pkgpartPages = packageCurrent.GetPart(New Uri(pagesPath, UriKind.Relative))
            If pkgpartPages IsNot Nothing Then
                '  Load the document XML in the part into an XDocument instance.
                Me.xDoc = XDocument.Load(XmlReader.Create(pkgpartPages.GetStream()))
            Else
                Exit Sub
            End If ' test for part found

            ' get the xml from the xDocument as an xElement
            Dim xelemPages As XElement = Me.xDoc.Elements.FirstOrDefault


            If xelemPageSummary IsNot Nothing Then
                xelemNewPage = xelemPageSummary
            End If


            xelemPages.Add(xelemNewPage)


            Me._xDoc = Nothing
            Me.xDoc = New XDocument
            ' put the updated xElement into the cleared xDocument
            Me.xDoc.Add(xelemPages)

            byteXML = uniEncoding.GetBytes(Me.xDoc.ToString)
            ' overwrite the windows package part with the updated data
            Using memStream As New MemoryStream(bufSize)
                memStream.Write(byteXML, 0, byteXML.Length)
                Me.visPackage.CopyStream(memStream, pkgpartPages.GetStream())
            End Using ' close the memory stream


        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub


    '
    ' adds page file to the package and then sets format to landscape
    '
    Public Sub addLandscapePageToPackage _
        (ByVal strPackagePath As String, _
         Optional ByVal intNewPageId As Integer = 0, _
         Optional ByVal strNewPageName As String = "Page-1", _
         Optional ByVal strNewPagePath As String = "page1.xml", _
         Optional ByVal strNewRid As String = "rId1")

        Try



            Dim tempVisPackage As clsVisPackage = New clsVisPackage
            ' go get the template and create an xElement out of it
            Dim xelemNewPage As XElement = XElement.Load((XmlReader.Create(New StringReader(clsPage.pageTemplateXML))))

            xelemNewPage.SetAttributeValue("ID", CStr(intNewPageId))
            xelemNewPage.SetAttributeValue("Name", strNewPageName)
            xelemNewPage.SetAttributeValue("NameU", strNewPageName)
            ' swap the x/y viewcenters
            xelemNewPage.SetAttributeValue("ViewCenterY", "4.25")
            xelemNewPage.SetAttributeValue("ViewCenterX", "7")


            Dim newCell As stcCell = New stcCell("", "", "", "")
            Dim qryPageSheet = xelemNewPage...<PageSheet>
            If qryPageSheet.Count = 1 Then

                ' start the element drilldown
                Dim listOfPageElements As IEnumerable(Of XElement) = _
                        From elemPage In xelemNewPage.Elements() _
                        Select elemPage
                Dim visCell As stcCell = New stcCell
                For Each elemPage As XElement In listOfPageElements

                    Select Case LCase(elemPage.Name.LocalName)
                        ' go into the page sheet
                        Case "pagesheet"

                            Dim listOfPageSheetElements As IEnumerable(Of XElement) = _
                            From elemPageSheet In elemPage.Elements() _
                            Select elemPageSheet

                            ' create a temp xdoc
                            Dim xdocTemp As XDocument = New XDocument
                            ' load the temp xdoc with the page sheet
                            xdocTemp.Add(elemPage)
                            ' create a shape object to put the pagesheet into
                            Dim visShape As clsShape = New clsShape
                            visShape.visPackage = tempVisPackage
                            visShape.xDoc = xdocTemp
                            visCell.Reset()
                            visCell.cellName = "PageWidth"
                            visCell.cellValue = "14"
                            visShape.setShapeCell("PageWidth", visCell)
                            visCell.Reset()
                            visCell.cellName = "PageHeight"
                            visCell.cellValue = "8.5"
                            visShape.setShapeCell("PageHeight", visCell)
                            visCell.Reset()
                            ' these two have to be added so that viso won't flip the page to portrait
                            visCell.cellName = "PaperKind"
                            visCell.cellValue = "5"
                            visShape.setShapeCell("PaperKind", visCell)
                            visCell.Reset()
                            visCell.cellName = "PrintPageOrientation"
                            visCell.cellValue = "2"
                            visShape.setShapeCell("PrintPageOrientation", visCell)

                            elemPage.ReplaceWith(visShape.xDoc.Elements.FirstOrDefault)

                    End Select ' page elements

                Next elemPage

            End If

            '
            ' open the package and add a pages pkgpart and a page pkgpart
            '
            Using package As Package = package.Open(strPackagePath, FileMode.Open, FileAccess.ReadWrite)

                Dim visPages As clsPages = New clsPages

                ' the default behaviour of this is to add the first page with a rId1 relationship
                visPages.addPortraitPageToPagesPkgPart(package, _
                                                       intNewPageId, _
                                                       strNewPageName, _
                                                       strNewPagePath, _
                                                       strNewRid, _
                                                       xelemNewPage)


                ' go find the pages packagepart.
                Dim pagesPath As String = "/visio/pages/pages.xml"
                Dim partUriPages As Uri = PackUriHelper.CreatePartUri(New Uri(pagesPath, UriKind.Relative))
                Dim pkgpartPages As PackagePart = package.GetPart(New Uri(pagesPath, UriKind.Relative))

                '**********************************************
                ' Add the Page part to the Package (pages packagepart)
                '**********************************************
                Dim visPage As clsPage = New clsPage
                visPage.visPackage = Me.visPackage
                visPage.addPageToPkgPart(package, pkgpartPages, strNewPagePath, strNewRid)

                visPage = Nothing
                visPages = Nothing

                package.Close()

            End Using

            GC.Collect()

        Catch xml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(xml, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub

    '
    ' adds page file to the package and then sets format to landscape
    '
    Public Sub addLandscapePageToPackage _
        (ByRef packageCurrent As Package, _
         Optional ByVal intNewPageId As Integer = 0, _
         Optional ByVal strNewPageName As String = "Page-1", _
         Optional ByVal strNewPagePath As String = "page1.xml", _
         Optional ByVal strNewRid As String = "rId1")

        Try



            Dim tempVisPackage As clsVisPackage = New clsVisPackage
            ' go get the template and create an xElement out of it
            Dim xelemNewPage As XElement = XElement.Load((XmlReader.Create(New StringReader(clsPage.pageTemplateXML))))

            xelemNewPage.SetAttributeValue("ID", CStr(intNewPageId))
            xelemNewPage.SetAttributeValue("Name", strNewPageName)
            xelemNewPage.SetAttributeValue("NameU", strNewPageName)
            ' swap the x/y viewcenters
            xelemNewPage.SetAttributeValue("ViewCenterY", "4.25")
            xelemNewPage.SetAttributeValue("ViewCenterX", "7")

            ' get the relationship id
            Dim listofElements As IEnumerable(Of XElement) = _
                From elem In xelemNewPage.Elements() _
                Select elem
            For Each elem As XElement In listofElements
                Select Case LCase(elem.Name.LocalName)
                    Case "rel"
                        Dim attrRID As XAttribute = elem.Attributes.FirstOrDefault
                        attrRID.Value = strNewRid
                End Select
            Next elem

            Dim newCell As stcCell = New stcCell("", "", "", "")
            Dim qryPageSheet = xelemNewPage...<PageSheet>
            If qryPageSheet.Count = 1 Then

                ' start the element drilldown
                Dim listOfPageElements As IEnumerable(Of XElement) = _
                        From elemPage In xelemNewPage.Elements() _
                        Select elemPage
                Dim visCell As stcCell = New stcCell
                For Each elemPage As XElement In listOfPageElements

                    Select Case LCase(elemPage.Name.LocalName)
                        ' go into the page sheet
                        Case "pagesheet"

                            Dim listOfPageSheetElements As IEnumerable(Of XElement) = _
                            From elemPageSheet In elemPage.Elements() _
                            Select elemPageSheet

                            ' create a temp xdoc
                            Dim xdocTemp As XDocument = New XDocument
                            ' load the temp xdoc with the page sheet
                            xdocTemp.Add(elemPage)
                            ' create a shape object to put the pagesheet into
                            Dim visShape As clsShape = New clsShape
                            visShape.visPackage = tempVisPackage
                            visShape.xDoc = xdocTemp
                            visCell.Reset()
                            visCell.cellName = "PageWidth"
                            visCell.cellValue = "14"
                            visShape.setShapeCell("PageWidth", visCell)
                            visCell.Reset()
                            visCell.cellName = "PageHeight"
                            visCell.cellValue = "8.5"
                            visShape.setShapeCell("PageHeight", visCell)
                            visCell.Reset()
                            ' these two have to be added so that viso won't flip the page to portrait
                            visCell.cellName = "PaperKind"
                            visCell.cellValue = "5"
                            visShape.setShapeCell("PaperKind", visCell)
                            visCell.Reset()
                            visCell.cellName = "PrintPageOrientation"
                            visCell.cellValue = "2"
                            visShape.setShapeCell("PrintPageOrientation", visCell)

                            elemPage.ReplaceWith(visShape.xDoc.Elements.FirstOrDefault)

                    End Select ' page elements

                Next elemPage

            End If

            Dim visPages As clsPages = New clsPages
            ' the default behaviour of this is to add the first page with a rId1 relationship


            visPages.addPortraitPageToPagesPkgPart(packageCurrent, _
                                                    intNewPageId, _
                                                    strNewPageName, _
                                                    strNewPagePath, _
                                                    strNewRid, _
                                                    xelemNewPage)

            ' go find the pages packagepart.
            Dim pagesPath As String = "/visio/pages/pages.xml"
            Dim partUriPages As Uri = PackUriHelper.CreatePartUri(New Uri(pagesPath, UriKind.Relative))
            Dim pkgpartPages As PackagePart = packageCurrent.GetPart(New Uri(pagesPath, UriKind.Relative))

            '**********************************************
            ' Add the Page part to the Package (pages packagepart)
            '**********************************************
            Dim visPage As clsPage = New clsPage
            visPage.visPackage = Me.visPackage
            visPage.addPageToPkgPart(packageCurrent, pkgpartPages, strNewPagePath, strNewRid)
            visPage = Nothing
            visPages = Nothing


            GC.Collect()

        Catch xml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(xml, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Notify Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub


#End Region

    '
    '
    '
    Public Sub New()



        Me.m_dictPagesNameU = Nothing
        Me.dictPagesNameU = New Dictionary(Of String, stcPageData)

        Me.m_dictPagesID = Nothing
        Me.dictPagesID = New Dictionary(Of Integer, stcPageData)

        Me._xDoc = Nothing
        Me.xDoc = New XDocument

        Me.m_visPackage = Nothing
        Me.visPackage = New clsVisPackage


    End Sub

    '
    '
    '
    Public Sub New(ByVal packageNew As clsVisPackage)

        Me.m_dictPagesNameU = Nothing
        Me.dictPagesNameU = New Dictionary(Of String, stcPageData)

        Me.m_dictPagesID = Nothing
        Me.dictPagesID = New Dictionary(Of Integer, stcPageData)

        Me._xDoc = Nothing
        Me.xDoc = New XDocument

        Me.m_visPackage = Nothing
        Me.visPackage = New clsVisPackage
        Me.visPackage = packageNew

    End Sub


    '
    '
    '
    Protected Overrides Sub Finalize()

        Me.m_dictPagesID = Nothing
        Me.m_dictPagesNameU = Nothing
        Me._xDoc = Nothing
        Me.m_visPackage = Nothing
        Me.m_visPage = Nothing

        GC.Collect()

        MyBase.Finalize()

    End Sub


End Class
